package xyz.quanguanjia.masterboy.message;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import xyz.quanguanjia.masterboy.ServiceType;
import xyz.quanguanjia.masterboy.adapter.MessageListAdapter;
import xyz.quanguanjia.masterboy.base.BaseFragment;
import xyz.quanguanjia.masterboy.MBDApplication;
import xyz.quanguanjia.masterboy.MBDHttpClient;
import xyz.quanguanjia.masterboy.MBDModelResponse;
import xyz.quanguanjia.masterboy.R;
import xyz.quanguanjia.masterboy.decoration.MessageItemDecoration;
import xyz.quanguanjia.masterboy.model.MBDMessageInfoModel;

public class MessageFragment extends BaseFragment implements MessageItemDecoration.MessageItemClickListener {

    private SmartRefreshLayout smartRefreshLayout;

    private ConstraintLayout notMessageCl;
    private RecyclerView recyclerView;
    private List<MBDMessageInfoModel> mBDMessageInfoModelList;

    private MessageListAdapter adapter;

    private int page = 1;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        this.getData("Refresh");
    }


    @Override
    public String fragmentTitle() {
        return "消息";
    }

    @Override
    public int fragmentIconId(int status) {
        if (status == BaseFragment.NORMAL) {
            return R.drawable.tab_message_nm;
        }
        if (status == BaseFragment.HIGHLIGHT) {
            return R.drawable.tab_message_hl;
        }
        return 0;

    }

    public void getData(String info) {
        if (info.equals("Refresh")) {
            page = 1;
            if (null == mBDMessageInfoModelList)
                mBDMessageInfoModelList = new ArrayList<>();
            mBDMessageInfoModelList.clear();
        } else {
            ++page;
        }
        this.doRequest(new CallBack() {
            @Override
            public void completion(List<MBDMessageInfoModel> details, boolean isShowLoad) {
                if (info.equals("Refresh")) {
                    smartRefreshLayout.finishRefresh(true);
                    notMessageCl.setVisibility((page == 1 && details.size() == 0) ? View.VISIBLE : View.GONE);
                    if (null != details && details.size() > 0) {
                        mBDMessageInfoModelList.addAll(details);
                        if (null == adapter) {
                            adapter = new MessageListAdapter(mBDMessageInfoModelList);
                            recyclerView.setAdapter(adapter);
                        }
                        adapter.notifyDataSetChanged();
                    }
                } else {
                    smartRefreshLayout.finishLoadMore(true);
                    if (null != details && details.size() > 0) {
                        mBDMessageInfoModelList.addAll(details);
                        adapter.notifyItemChanged(mBDMessageInfoModelList.size() - details.size() + 1);
                    }
                }
                smartRefreshLayout.setNoMoreData(isShowLoad);
            }
        });
    }

    private void doRequest(CallBack callBack) {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("pageNum", this.page + "");
        MBDHttpClient.shared().doRequest(ServiceType.SERVICE_MESSAGE_LIST, params, new MBDHttpClient.Callback() {
            @Override
            public void completion(boolean success, Error error, MBDModelResponse response) {
                if (success) {
                    ArrayList list = (ArrayList) response.data;
                    ArrayList resultArrayList = new ArrayList<MBDMessageInfoModel>();
                    for (int i = 0; i < list.size(); i++) {
                        LinkedTreeMap<String, Object> linkedTreeMap = (LinkedTreeMap<String, Object>) list.get(i);
                        Gson gson = new Gson();
                        String jsonString = gson.toJson(linkedTreeMap);
                        MBDMessageInfoModel detail = gson.fromJson(jsonString, MBDMessageInfoModel.class);
                        resultArrayList.add(detail);
                    }
                    callBack.completion(resultArrayList, response.total == list.size() + mBDMessageInfoModelList.size());
                }
            }
        });
    }


    @Override
    public void onItemClick(int position) {
    }

    public interface CallBack {
        public void completion(List<MBDMessageInfoModel> details, boolean isShowLoad);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_message, container, false);
        notMessageCl = view.findViewById(R.id.not_message_cl);
        notMessageCl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getData("Refresh");
            }
        });
        smartRefreshLayout = view.findViewById(R.id.refresh_layout);
        this.recyclerView = view.findViewById(R.id.recyclerView);
        mBDMessageInfoModelList = new ArrayList<>();
        //下拉刷新上拉加载更多
        setHeaderOrFooter();


        LinearLayoutManager layoutManager = new LinearLayoutManager(MBDApplication.getContext());
        recyclerView.setLayoutManager(layoutManager);
        MessageItemDecoration hi = new MessageItemDecoration(this);
        recyclerView.addItemDecoration(hi);
        recyclerView.addItemDecoration(new DividerItemDecoration(MBDApplication.getContext(), LinearLayoutManager.VERTICAL));

        return view;

    }


    private void setHeaderOrFooter() {
        if (null != requireActivity()) {
            smartRefreshLayout.setRefreshHeader(new ClassicsHeader(requireActivity()));
            smartRefreshLayout.setRefreshFooter(new ClassicsFooter(requireActivity()));
            smartRefreshLayout.setOnRefreshListener(refreshLayout -> {
                getData("Refresh");
            });
            smartRefreshLayout.setOnLoadMoreListener(refreshLayout -> getData("load"));
        }
    }
}
